package treemodel.unit;

import document.AttributeSet;
import document.Context;
import treemodel.Unit;
import treeview.NodeView;
import treeview.unit.TextView;

import java.util.ArrayList;

/**
 * Created by Pavel Nikolaev
 */
public class TextUnit extends Unit {
    private char[] mySource;
    private int myOffset;
    private int myLength;
    private AttributeSet myAttributeSet;

    public TextUnit(String source, int offset, int length, AttributeSet set) {
        this(source.toCharArray(), offset, length, set);
    }

    public TextUnit(char[] source, int offset, int length, AttributeSet set) {
        this.mySource = source;
        this.myOffset = offset;
        this.myLength = length;
        this.myAttributeSet = set;
    }

    @Override
    public ArrayList<Unit> breakToWords() {
        ArrayList<Unit> words = new ArrayList<Unit>();
        int wordStartOffset = myOffset;
        int endOffset = myOffset + myLength;
        for (int i = myOffset; i < endOffset; ++i) {
            if (mySource[i] == ' ') {
                words.add(new TextUnit(mySource, wordStartOffset, i - wordStartOffset + 1, myAttributeSet));
                wordStartOffset = i + 1;
            }
        }
        if (wordStartOffset != myOffset + myLength)
            words.add(new TextUnit(mySource, wordStartOffset, endOffset - wordStartOffset, myAttributeSet));
        return words;
    }

    public NodeView createView(Context context) {
        return new TextView(mySource, myOffset, myLength, myAttributeSet, context);
    }
}
